using BackData;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Roles;

namespace Team.API.Applocation.Handler.Users.Roles
{
    /// <summary>
    /// 删除角色处理器
    /// </summary>
    public class DeleteRoleHandler : IRequestHandler<DeleteRoleCommand, APIResult<int>>
    {
        private readonly IRepository<Rolemodel> roleRepository;
        private readonly IRepository<Usermodel> userRepository;

        public DeleteRoleHandler(
            IRepository<Rolemodel> roleRepository,
            IRepository<Usermodel> userRepository)
        {
            this.roleRepository = roleRepository;
            this.userRepository = userRepository;
        }

        public async Task<APIResult<int>> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
        {
            // 查询角色是否存在
            var role = await roleRepository.GetByIdAsync(request.Id);
            if (role == null || role.IsDel)
            {
                return APIResult<int>.Faile("角色不存在");
            }


            // 检查是否有用户使用该角色
            bool hasUsers = await userRepository.GetAll()
                .Where(u => u.IsDel == false && u.RoleId == request.Id)
                .AnyAsync();

            if (hasUsers)
            {
                return APIResult<int>.Faile("该角色下有用户，无法删除");
            }

            // 软删除角色
            role.IsDel = true;
            //role.Updatedate = DateTime.Now;
            //role.Updatename = "系统管理员"; // TODO: 从当前登录用户获取

            int rows = await roleRepository.UpdateAsync(role);
            if (rows <= 0)
            {
                return APIResult<int>.Faile("删除角色失败");
            }

            return APIResult<int>.Ok("删除角色成功", rows);
        }
    }
}
